//
//  LMRodioPlayController.m
//  EPA
//
//  Created by lanou3g on 16/4/21.
//  Copyright © 2016年 liman. All rights reserved.
//

#import "LMRodioPlayController.h"

#import "AppDelegate.h"
#import "LMRadioListModel.h"
#import "LMAVManager.h"
#import "DownLoadManager.h"

#import "LMMusicWordController.h"
#import "LMDownLoadController.h"
@interface LMRodioPlayController ()<UIGestureRecognizerDelegate>


@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIImageView *covImageView;
@property (weak, nonatomic) IBOutlet UISlider *rateSilder;


@property (weak, nonatomic) IBOutlet UIImageView *songImgView;

@property (weak, nonatomic) IBOutlet UILabel *tatolLabel;

@property (weak, nonatomic) IBOutlet UIButton *palyBtn;

///计时器
@property (nonatomic,strong) NSTimer *playTimer;
///动画设置
@property (nonatomic, strong) CAKeyframeAnimation *ani;

@end

@implementation LMRodioPlayController

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    self.covImageView.layer.cornerRadius = 228;
//    self.covImageView.clipsToBounds = YES;
     [self transformImageView:self.covImageView];
}

- (void)viewDidLoad {
    [super viewDidLoad];
//    设置导航栏的透明度
//    self.navigationController.navigationBar.translucent = NO;



    
    
    LMRadioListModel * model = self.radioArray[self.currentIndex];
    self.titleLabel.text  = model.title;
    [self.covImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
    
    self.covImageView.alpha = 0.7;
     [self.songImgView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
    
    [self.covImageView setUserInteractionEnabled:YES];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(panMenuWithswipeGesture:)];

    [self.covImageView addGestureRecognizer:tap];
    
    [LMAVManager shareManager].currentIndex = self.currentIndex;
    /*
     穿过来数组里面包含的是model
     播放时 需要的数组是 音乐的url
     所以要下面这样取出来
     */
    NSMutableArray *itemArray = [NSMutableArray new];
    for (LMRadioListModel *model in self.radioArray) {
        NSURL *musicUrl = [NSURL URLWithString:model.playInfoModel.musicUrl];
        AVPlayerItem *item = [AVPlayerItem playerItemWithURL:musicUrl];
        [itemArray addObject:item];
    }
    
    [LMAVManager shareManager].itemArray = itemArray;
    [[LMAVManager shareManager] play];
    
//    初始化timer
    self.playTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(timeAction) userInfo:nil repeats:YES];
      [[NSRunLoop currentRunLoop] addTimer:_playTimer forMode:NSDefaultRunLoopMode];
//    观察者
    [self addObserver];
    
//    下载列表
    UIBarButtonItem *downListItem =  [[UIBarButtonItem alloc]initWithTitle:@"下载列表" style:UIBarButtonItemStylePlain target:self action:@selector(downLoadButtonAction:)];
    self.navigationItem.rightBarButtonItem = downListItem;
    
}

- (void)downLoadButtonAction:(UIBarButtonItem *)item{
    LMDownLoadController *downVC = [[LMDownLoadController alloc]init];

    [self.navigationController pushViewController:downVC animated:YES];
}

- (void)panMenuWithswipeGesture:(UITapGestureRecognizer *)tap {
    LMMusicWordController *wordVC = [[LMMusicWordController alloc]init];
    LMRadioListModel *model = self.radioArray[self.currentIndex];
    wordVC.name = model.title;
    [self.navigationController pushViewController:wordVC animated:YES];
}


//时间显示
- (void)timeAction{

    // 给Slider赋值
    self.rateSilder.minimumValue = 0;
    self.rateSilder.maximumValue = [LMAVManager shareManager].totalTime;
    self.rateSilder.value = [LMAVManager shareManager].currentTime;
    // 显示剩余时长
    self.tatolLabel.text= [NSString stringWithFormat:@"%02lld : %02lld",(int64_t)([LMAVManager shareManager].totalTime -[LMAVManager shareManager].currentTime) / 60, (int64_t)([LMAVManager shareManager].totalTime - [LMAVManager shareManager].currentTime) % 60];
}

- (IBAction)didClickDownloadAction:(UIButton *)sender {
    
    LMRadioListModel *model = self.radioArray[self.currentIndex];
    [[DownLoadManager shareManager]addDownloadTask:model Progress:nil Complete:nil];
    
}

//播放进度

- (IBAction)didChangePlayRate:(UISlider *)sender {
     CMTime changeTime = CMTimeMake(sender.value  * [LMAVManager shareManager].player.currentItem.duration.value , [LMAVManager shareManager].player.currentItem.duration.timescale);
    
    [[LMAVManager shareManager]seekToTime:changeTime];
  
}

//上一曲

- (IBAction)didChangePreviousAction:(UIButton *)sender {
    [[LMAVManager shareManager]previous];
//    图片和标题
    self.currentIndex --;
    if (self.currentIndex < 0) {
        self.currentIndex = self.radioArray.count - 1;
    }
     LMRadioListModel *model = self.radioArray[self.currentIndex];
    [self.covImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
      [self.songImgView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
    [self transformImageView:self.covImageView];
    self.titleLabel.text = model.title;
    
    [self.palyBtn setImage:[UIImage imageNamed:@"ting"] forState:UIControlStateNormal];
}

//播放 暂停

- (IBAction)didChangePlayAction:(UIButton *)sender {
    if ([LMAVManager shareManager].player.rate == 0) {
        [[LMAVManager shareManager]play];
        [sender setImage:[UIImage imageNamed:@"ting"] forState:UIControlStateNormal];
        [self transformImageView:self.covImageView];
    }else{
        [[LMAVManager shareManager]pause];
        [sender setImage:[UIImage imageNamed:@"play"] forState:UIControlStateNormal];
        [self.covImageView.layer removeAllAnimations];
    }
}

//下一曲

- (IBAction)didChangeNextAction:(id)sender {
    [self playNext];
}


#pragma mark - 旋转动画
- (void)transformImageView:(UIImageView *)imgView{
    imgView.layer.cornerRadius = 150;
    imgView.clipsToBounds = YES;
    CAKeyframeAnimation *ani = [CAKeyframeAnimation animationWithKeyPath:@"transform.rotation"];
    CGFloat point = M_PI_4;
    ani.values = @[@(9 * point),@(8 * point),@(7 * point),@(6 * point),@(5 * point),@(4 * point),@(3 * point),@(2 * point),@(point)];
    ani.repeatCount = MAXFLOAT;
    
    ani.duration = 9;
    self.ani = ani;
    
    [imgView.layer addAnimation:ani forKey:@"xuanzhuan"];
}

#pragma mark - 注册观察者

- (void)addObserver{
  
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playNext) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];

}

- (void)playNext{
    [[LMAVManager shareManager] next];
    
    self.currentIndex ++;
    if (self.currentIndex >= self.radioArray.count) {
        self.currentIndex = 0;
    }
    LMRadioListModel *model = self.radioArray[self.currentIndex];
    [self.covImageView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
    [self transformImageView:self.covImageView];
      [self.songImgView sd_setImageWithURL:[NSURL URLWithString:model.coverimg]];
    self.titleLabel.text = model.title;
    
    [self.palyBtn setImage:[UIImage imageNamed:@"ting"] forState:UIControlStateNormal];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


@end
